package xyz.riceball.security.authentication;

import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import xyz.riceball.framework.core.bean.ApiR;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 异常处理 异常流程
 * </p>
 *
 * @author xiaovcloud
 * @since 2022/7/12 23:10
 */
@Slf4j
public class RiceBallAuthExceptionHandler implements AccessDeniedHandler, AuthenticationEntryPoint {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException, ServletException {
        log.info("权限发生异常，如下：", exception);
        response.setStatus(HttpStatus.HTTP_INTERNAL_ERROR);
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        if (exception instanceof AuthorizationServiceException) {
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorCodeAndMsg(403, exception.getMessage())));
        } else {
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorMsg(exception.getMessage())));
        }
        response.getWriter().flush();
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("权限发生异常，如下：", exception);
        response.setStatus(HttpStatus.HTTP_INTERNAL_ERROR);
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        if (exception instanceof AccountExpiredException) {
            response.setStatus(401);
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorCodeAndMsg(401, exception.getMessage())));
        } else if (exception instanceof AuthenticationServiceException) {
            response.setStatus(403);
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorCodeAndMsg(403, exception.getMessage())));
        } else {
            response.getWriter().print(JSONUtil.toJsonStr(ApiR.errorMsg(exception.getMessage())));
        }
        response.getWriter().flush();
    }


}
